#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QDebug>
#include "logger.h"

Logger* Logger::mInstance = NULL;

// default logfile name
QString Logger::logFileName = QString("%1%2%3")
        .arg(QDir::currentPath())
        .arg(QDir::separator())
        .arg("log.htm");

void Logger::CreateInstance()
{ // Singletone idea. If no instance -- create it
    if (mInstance == NULL)
        mInstance = new Logger();
}

void Logger::DestroyInstance()
{ // Singletone idea. If there is instance -- create it
    if (mInstance != NULL)
        delete mInstance;
}

Logger::Logger()
{ // Instance constructor
    logFile.setFileName(logFileName);
    if (!logFile.open(QIODevice::WriteOnly))
        return;
}

Logger::~Logger()
{ // Instance destructor
    logFile.close();
}

QString Logger::formatLog(const QString &who, const QString &what, const QString &comment) const
{
    return (comment.isEmpty()||comment.isNull())
            ? QString("<b>(%1)</b> %2<br/>").arg(who).arg(what)
            : QString("<b>(%1)</b> %2, <i>%3</i><br/>").arg(who).arg(what).arg(comment);
}

void Logger::add(const QString &who, const QString &what, const QString &comment)
{
    QTextStream out(&logFile);
    out<<formatLog(who, what, comment);

    qDebug() << who << " " << what << " " << comment;
}

Logger * Logger::instance()
{// Singletone idea. Returning instance
    return mInstance;
}
